﻿using HY.Common;
using HY.Model;
using HY.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Linq.Expressions;
using System.Security.Claims;

namespace HY.Web.Controllers
{
    public class SysUserController : BaseController
    {
        public SysUserController(ILogger<SysUserController> logger) : base(logger)
        {
        }

        [Authorize]
        public ActionResult Index()
        {
            return View();
        }
        [Authorize]
        [HttpPost]
        public JsonResult Index(SysUser model, int pageIndex, int pageSize)
        {
            Expression<Func<SysUser, bool>> filter = e => e.IsDelete == false && e.RoleId != 0;
            if (!string.IsNullOrEmpty(model.UserName))
                filter = filter.And(c => c.UserName.Contains(model.UserName));
            if (model.RoleId != 0)
                filter = filter.And(c => c.RoleId == model.RoleId);
            if (!string.IsNullOrEmpty(model.TrueName))
                filter = filter.And(c => c.TrueName.Contains(model.TrueName));
            if (!string.IsNullOrEmpty(model.PhoneNumber))
                filter = filter.And(c => c.PhoneNumber.Contains(model.PhoneNumber));
            int totalCount = 0;
            var list = DbContext.db.Queryable<SysUser>().Where(filter).OrderBy(o => o.Id, OrderByType.Desc).ToPageList(pageIndex, pageSize, ref totalCount);
            return Json(Success(totalCount, list));
        }

        [AllowAnonymous]
        public IActionResult EditPassword()
        {
            return View();
        }

        [AllowAnonymous]
        [HttpPost]
        public JsonResult EditPassword(string oldPsw, string newPsw)
        {
            int id = int.Parse(User.FindFirstValue(SystemConst.CookieKey.UserId));
            SysUser model = DbContext.SysUser.GetById(id);
            if (model.Password == StringHelper.MD5Encrypt(oldPsw))
            {
                model.Password = StringHelper.MD5Encrypt(newPsw);
                model.UpdateTime = DateTime.Now;
                DbContext.db.Updateable(model).UpdateColumns(it => new { it.Password, it.UpdateTime }).ExecuteCommand();
                return Json(returnModel);
            }
            else
            {
                returnModel.Code = 0;
                returnModel.Message = "原密码错误";
            }
            return Json(returnModel);
        }

        public IActionResult Add()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Add(SysUser model)
        {
            if (DbContext.SysUser.GetFirst(c => c.UserName == model.UserName) == null)
            {
                model.Password = StringHelper.MD5Encrypt("123456");
                DbContext.SysUser.Insert(model);
            }
            else
            {
                returnModel.Code = 0;
                returnModel.Message = "账号名已存在";
            }
            return Json(returnModel);
        }

        public IActionResult Edit(int id)
        {
            var model = DbContext.SysUser.GetById(id);
            return View(model);
        }

        [HttpPost]
        public IActionResult Edit(SysUser model)
        {
            if (DbContext.SysUser.GetFirst(c => c.UserName == model.UserName && c.Id != model.Id) == null)
                DbContext.db.Updateable(model).IgnoreColumns(it => new { it.AddTime, it.Password }).ExecuteCommand();
            else
            {
                returnModel.Code = 0;
                returnModel.Message = "账号名已存在";
            }
            return Json(returnModel);
        }

        [HttpPost]
        public IActionResult Delete(long id)
        {
            DbContext.db.Updateable<SysUser>().SetColumns(it => it.IsDelete == true).Where(it => it.Id == id).ExecuteCommand();
            return Json(returnModel);
        }
        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PasswordReset(long[] ids)
        {
            string password = StringHelper.MD5Encrypt("123456");
            DbContext.db.Updateable<SysUser>().SetColumns(it => it.Password == password).Where(it => ids.Contains(it.Id)).ExecuteCommand();
            return Json(returnModel);
        }
    }
}
